package com.anteater.eattheant.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Ranking {
	private RankingOpenHelper rankingOpenHelper;

	public Ranking(Context ctx) {
		rankingOpenHelper = new RankingOpenHelper(ctx);
	}

	public Score getScore(int level) {
		SQLiteDatabase database = rankingOpenHelper.getReadableDatabase();
		Cursor query = database.query("score",
				new String[] { "level", "score" }, "level = ?",
				new String[] { "" + level }, null, null, null, null);

		Score score = null;

		if (!query.isAfterLast()) {
			query.moveToNext();
			score = new Score(query.getInt(0), query.getInt(1));
		}

		query.close();
		database.close();

		return score;
	}

	public Integer getMaxLevel() {
		SQLiteDatabase database = rankingOpenHelper.getReadableDatabase();

    	Cursor query = database.query("score", new String[] { "MAX(level)",
				"COUNT(level)" }, null, null, null, null, null, null);

		Integer level = null;

		query.moveToNext();
		if (new Integer(query.getInt(1)) > 0) {
			level = new Integer(query.getInt(0));
		}

		query.close();
		database.close();

		return (level == null ? 0 : level);
	}

	public boolean addScore(Score score) {
		Score old = getScore(score.getLevel());

		if (old != null && old.getScore() >= score.getScore()) {
			return false;
		}

		ContentValues value = new ContentValues();
		value.put("level", score.getLevel());
		value.put("score", score.getScore());
		SQLiteDatabase database = rankingOpenHelper.getWritableDatabase();

		if (old == null) {
			database.insert("score", null, value);
		} else {
			database.update("score", value, "level = ?", new String[] { ""
					+ score.getLevel() });
		}

		database.close();

		return true;
	}

	private class RankingOpenHelper extends SQLiteOpenHelper {
		private static final String DATABASE_NAME = "eattheant";
		private static final int DATABASE_VERSION = 1;
		private static final String TABLE_NAME = "score";

		public RankingOpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + TABLE_NAME
					+ " (level INTEGER, score INTEGER);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}
		
	}
}
